package cn.news.xinhuanet.application.exception;

import cn.news.xinhuanet.utils.ToolUtils;
import net.sf.json.JSONObject;
import org.apache.log4j.Logger;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.SimpleMappingExceptionResolver;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.io.PrintWriter;

public class HomeHandlerExceptionResolver extends SimpleMappingExceptionResolver {

    private static Logger logger = Logger.getLogger(HomeHandlerExceptionResolver.class);

    private String readException(Exception ex) {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        PrintStream pout = new PrintStream(out);
        ex.printStackTrace(pout);
        String ret = new String(out.toByteArray());
        pout.close();
        try {
            out.close();
        } catch (Exception e) {
        }
        return ret;
    }

    @Override
    protected ModelAndView doResolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        logger.error(ex.getMessage(), ex);
//		EmailUtils.sendEmail("383551006@qq.com","系统异常",readException(ex));
        // 如果不是异步请求
        if (ToolUtils.isAjax(request) == false) {
            String viewName = determineViewName(ex, request);
            Integer statusCode = determineStatusCode(request, viewName);
            if (statusCode != null) {
                applyStatusCodeIfPossible(request, response, statusCode);
            }
            ModelAndView model = getModelAndView(viewName, ex, request);
            return model;
        }
        // JSON格式返回(待测)
        try {
            JSONObject json = new JSONObject();
            json.put("code", 500);
            json.put("msg", "操作失败，请重试或告诉我们");
            PrintWriter writer = response.getWriter();
            writer.print(json);
            writer.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

}
